<?php

namespace app\admin\controller;

use think\Controller;

class Api extends Controller {

	/**
	 * 提现代付
	 * @author lukui  2017-09-05
	 * @param  [type] $balance  提现列表
	 * @param  [type] $userinfo 用户名称
	 * @param  [type] $bank     银行账户
	 * @return [type]           返回信息
	 */
	private function daifuConfig() {
		return array(
			"MerchantID" => "MD201710200000001136", //商户编号
			"md5Key" => "rU7eLccS523K2TVDMNIQR0SxAArvgvsh", //md5密钥
			"payUrl" => "http://www.bisrec.com/aggpay/gateway/api/pay", //post提交接口
			"AppID" => "", //公众号appid
			"OpenID" => "", //微信openid
			"NotifyUrl" => "http://{$_SERVER['HTTP_HOST']}/index/pay/juhenotify.html", //异步通知地址
			"ReturnUrl" => "http://{$_SERVER['HTTP_HOST']}/index/index/index.html", //同步返回地址
			"PayPwd" => "123456", //支付密码	（支付密码+工作密钥）MD5加密,商户必填
			"PwdKey" => "VOSZVO2JXM2JPZ03AV6X6YCTNA00FSVN", //支付密码	（支付密码+工作密钥）MD5加密,商户必填
		);
	}

	public function daifu($balance, $userinfo, $bank) {

		//是否已经提现
		if ($balance['isverified'] != 9) {
			return WPreturn('该订单已处理!', -1);
		}
		$daifuConfig = $this->daifuConfig();

		//代付信息
		header("Content-Type:text/html;charset=utf-8");
		$data = array(
			"TradeType" => "bis.pay.payment", //N	交易类型	bis.pay.payment
			"OperatorID" => $daifuConfig['MerchantID'], //Y操作员	默认商户编号
			"PayType" => "0101", //N支付类型	"0101-单笔实时代付
			"TerminalType" => "PC", //Y终端类型 Android;IOS;PC;Others
			"PayPWD" => md5($daifuConfig['PayPwd'] . $daifuConfig['PwdKey']), //N支付密码	（支付密码+工作密钥）MD5加密,商户必填
			"MerchantID" => $daifuConfig['MerchantID'], //N商户编号
			"BankID" => "", //Y银行代码	存折必须填写
			//"OrderID" => $balance['bpid'] . '_' . $balance['bptime'], //N	订单号
			"OrderID" => $balance['bpid'] . '_' .  time(), //N	订单号
			"BankAccountType" => "00", //Y	银行账户类型	00银行卡，01存折，02信用卡。不填默认为银行卡00。
			"BankAccountNo" => $bank['accntno'], //N	银行账号
			"BankAccountName" => $bank['accntnm'], //N	银行账户名称
			"Province" => "", //Y	开户行所在省
			"City" => "", //Y	开户行所在市	如北京市，不能填北京
			"BankName" => $bank['bank_nm'], //Y	开户行名称
			"AccountProp" => "0", //Y	账号属性	0-对私 1-对公
			"CardType" => "0", //Y	开户证件类型 0:身份证,1:户口簿，2:护照,3.军官证,4.士兵证，5. 港澳居民来往内地通行证,6. 台湾同胞来往内地通行证,7. 临时身份证,8. 外国人居留证,9. 警官证,A.组织机构代码证，B.三证合一 X.其他证件
			"CardNum" => $bank['scard'], //Y	证件号码
			"Tel" => $bank['phone'], //Y	手机号码（预留在银行的）
			"BranchBankID" => "", //Y	支行号	见附件
			"DeviceID" => "", //Y	设备号	
			"MachineIP" => $this->getClientIp(), //N	终端IP	订单生成的机器IP
			"NotifyUrl" => "http://{$_SERVER['HTTP_HOST']}/admin/api/daifurefund.html", //N	通知地址
			"SubmitTime" => date("YmdHis"), //N	订单提交时间	格式：yyyyMMddHHmmss
			"Amt" => sprintf("%.2f", round($balance['bpprice'] * (100 - $balance['reg_par']) / 100, 2))*100, //N	交易金额	单位为分，不含小数点
				
			"Summary" => "提现转账", //Y	交易附言
			//"Sign" => "bis.pay.payment",
		);

		$data = $this->paraFilter($data);
		$data['Sign'] = $this->juheSign($data, $daifuConfig['md5Key']);
		//$this->curlPost($daifuConfig['payUrl'], $data);
		$Reply = $this->curlPost($daifuConfig['payUrl'], $data);
		$result = array();
		parse_str($Reply, $result);
		/*
		  PlatSerial	String(40)	Y	平台交易流水号
		  OperatorID	String(40)	Y	操作员ID
		  OrderID	String(40)	N	订单号
		  MerchantID	String(40)	Y	商户编号
		  Amt	String(16)	Y	交易金额	单位为分，不含小数点
		  Sign	String(32)	N	签名,详见数据签名说明
		  RetStatus	String(4)	N	业务状态	0表示接受，1或者其他标识未接受
		  RetDesc	String(128)	Y	状态描述
		  RetCode	String(4)	N	返回代码	参照返回码
		  RetMsg	String(128)	Y	描述信息
		 */
		file_put_contents("juhepay.log", date("Y-m-d H:i:s").":".var_export($data, true)."\r\n", FILE_APPEND);
		file_put_contents("juhepay.log", date("Y-m-d H:i:s").":".var_export($Reply, true)."\r\n", FILE_APPEND);
		if ($result['RetStatus'] == '0') {
			return WPreturn($result['RetMsg'], 1);
		} else {
			return WPreturn($result['RetMsg'], -1);
		}
	}

	public function daifurefund() {
		date_default_timezone_set('PRC');
		error_reporting(0);
		set_time_limit(0);
		$juheConfig = $this->juheConfig();
		file_put_contents("juhepay.log", var_export($_POST, true), FILE_APPEND);
		if ($this->juheSignVerify($_POST, $juheConfig['md5Key'])) {
			$notifyArray = array(// 返回字段
				"RetStatus" => $_POST["RetStatus"], // 返回状态  //0表示成功非0表示失败此字段是通信标识，非交易标识，交易是否成功需要查看 DealStatus 来判断
				"RetDesc" => $_POST["RetDesc"], // 状态描述
				"DealStatus" => $_POST["DealStatus"], // 交易状态  //0已支付，1未支付，其他失败
				"RetCode" => $_POST["RetCode"], // 返回码
				"RetMsg" => $_POST["RetMsg"], //描述
				"Sign" => $_POST["Sign"], //签名,详见数据签名说明
				"PayType" => $_POST["PayType"], //支付类型  0203-微信扫码支付;0204-支付宝扫码支付;0205-微信app支付;0207-微信公众号支付
				"MerchantID" => $_POST["MerchantID"], //商户编号
				"OrderID" => $_POST["OrderID"], //订单号
				"Subject" => $_POST["Subject"], //商品名称
				"TradeTime" => $_POST["TradeTime"], //订单交易时间  格式：yyyyMMddHHmmss
				"Amt" => $_POST["Amt"], //交易金额  单位为分，不含小数点
				"Summary" => $_POST["Summary"], //交易附言
				"Status" => $_POST["Status"], //订单状态  01：未支付 ；02：已支付；03：已关闭；04：支付失败；05：订单超时；
			);
			if ($notifyArray['RetCode'] == '0000') {
				//提现成功
				$_data['isverified'] = 1;
			} else {
				$_data['isverified'] = -1;
				$_data['remarks'] = $notifyArray['RetMsg'];
			}
			file_put_contents("juhepay.log", "SUCCESS", FILE_APPEND);
			echo "SUCCESS";
		} else {
			file_put_contents("juhepay.log", "验签失败", FILE_APPEND);
			echo "验签失败";
			$_data['isverified'] = -1;
			$_data['remarks'] = "签名验证失败";
		}

		
		//处理提现申请
		$res_order = explode("_", $notifyArray['OrderID']);
		if ($res_order == 2) {
			$_data['bpid'] = $res_order[0];
		} else {
			$_data['bpid'] = 7130;  //测试失误，但是要成功！
		}
		db('balance')->update($_data);






/*
		//以下是post接受的传递过来的参数
		$merId = $_POST['merId'];   //商户号
		$userOrder = $_POST['userOrder']; //接收传递的订单号
		$money = $_POST['money'];   //金额
		$resultCode = $_POST['resultCode'];   //状态码
		$resultMsg = $_POST['resultMsg']; //返回错误
		$date = $_POST['date'];   //时间
		$chkValue = $_POST['chkValue'];  //获取签名串
		$sn = "ca5b1fa291";   //商户密匙（form表单中未提交在这重新输入值进行验证）
		$md55 = md5($merId . $userOrder . $money . $resultCode . $resultMsg . $date . $sn); //利用商户密匙重新生成md5加密串与接受的签名串进行验证

		if ($resultCode == "0000") {   //判断返回的提现状态
			if ($md55 == $chkValue) { //判断MD5加密串是否正确（利用商户密匙）
				$_data['isverified'] = 1;
				printf('success');  //打印流水号给支付系统检索用来确认商户系统已经收到该笔流水号的交易返回应答
			}
		} else {
			$_data['isverified'] = -1;
			$_data['remarks'] = $resultMsg;
		}

		$res_order = explode("_", $userOrder);
		if ($res_order == 2) {
			$_data['bpid'] = $res_order[0];
		} else {
			$_data['bpid'] = 7130;  //测试失误，但是要成功！
		}
		db('balance')->update($_data);
		
		*/
	}

	/*

	  public function daifu($balance,$userinfo,$bank)
	  {

	  //是否已经提现
	  if($balance['isverified'] != 0){
	  return WPreturn('该订单已处理!',-1);
	  }


	  //代付信息
	  header("Content-Type:text/html;charset=utf-8");
	  $data['merId'] = 'M1708231621510004';
	  $data['userId'] = '13378685767';
	  $data['carId'] = $bank['accntno'];
	  $data['openName'] = $bank['accntnm'];
	  $data['openBank'] = $bank['bank_nm'];
	  $data['userOrder'] = $balance['bpid'].'_'.$balance['bptime'];
	  $data['phone'] =$bank['phone'];
	  $data['liqType'] = 'T0';
	  $data['openBank'] = $bank['bank_nm'];
	  $data['voucher'] = "身份证";
	  $data['voucherId'] = $bank['scard'];
	  $data['reqUrl'] = "http://".$_SERVER['SERVER_NAME']."/admin/api/daifurefund.html";
	  $data['money'] = sprintf("%.2f",round($balance['bpprice']*(100-$balance['reg_par'])/100,2));


	  $sn			= 'ca5b1fa291';
	  $data['reqType']='payWith';
	  //签名串
	  $chkValue=md5($data['reqType'].$data['merId'].$data['userId'].$data['userOrder'].$data['money'].$data['reqUrl'].$data['carId'].$data['openName'].$data['openBank'].$data['phone'].$data['voucher'].$data['voucherId'].$sn);

	  $data['chkValue']=$chkValue;

	  $url="http://pay.goldepay.cn/mobile/wdl/payWith.do";


	  $ch = curl_init ();
	  curl_setopt ( $ch, CURLOPT_URL,$url);//抓取指定网页
	  curl_setopt ( $ch, CURLOPT_POST, 1 );//设置header
	  curl_setopt ( $ch, CURLOPT_HEADER, 0 );//设置header
	  curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );//要求结果为字符串且输出到屏幕上
	  curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data);
	  $return = curl_exec ( $ch );
	  curl_close ( $ch );


	  $arr = json_decode($return,1);

	  if($arr['resultCode'] == '0000'){
	  return WPreturn($arr['resultMsg'],1);
	  }else{
	  return WPreturn($arr['resultMsg'],-1);
	  }


	  }


	  public function daifurefund()
	  {


	  //以下是post接受的传递过来的参数
	  $merId 		= $_POST['merId'];   		 //商户号
	  $userOrder 	= $_POST['userOrder']; 		 //接收传递的订单号
	  $money		= $_POST['money']; 		 	 //金额
	  $resultCode	=$_POST['resultCode'];	     //状态码
	  $resultMsg	=$_POST['resultMsg']; 	     //返回错误
	  $date		=$_POST['date'];  			 //时间
	  $chkValue 	= $_POST['chkValue'];  		 //获取签名串
	  $sn			= "ca5b1fa291";  						 //商户密匙（form表单中未提交在这重新输入值进行验证）
	  $md55		= md5($merId.$userOrder.$money.$resultCode.$resultMsg.$date.$sn);//利用商户密匙重新生成md5加密串与接受的签名串进行验证

	  if($resultCode == "0000"){  			 //判断返回的提现状态
	  if($md55 == $chkValue){  				 //判断MD5加密串是否正确（利用商户密匙）
	  $_data['isverified'] = 1;
	  printf('success');				 //打印流水号给支付系统检索用来确认商户系统已经收到该笔流水号的交易返回应答
	  }
	  }else{
	  $_data['isverified'] = -1;
	  $_data['remarks'] = $resultMsg;
	  }

	  $res_order = explode("_", $userOrder);
	  if($res_order == 2){
	  $_data['bpid'] = $res_order[0];
	  }else{
	  $_data['bpid'] = 7130; 	//测试失误，但是要成功！
	  }
	  db('balance')->update($_data);

	  } */

	public function getClientIp() {
		if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
			$ip = getenv('HTTP_CLIENT_IP');
		} elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
			$ip = getenv('HTTP_X_FORWARDED_FOR');
		} elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
			$ip = getenv('REMOTE_ADDR');
		} elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		preg_match("/[\d\.]{7,15}/", $ip, $onlineipmatches);
		$ip = empty($onlineipmatches[0]) ? 'unknown' : $onlineipmatches[0];
		return $ip;
	}

	public function paraFilter($para) {
		$para_filter = array();
		while (list ($key, $val) = each($para)) {
			if ($key == "Sign" || $key == "sign_type" || $val == "")
				continue;
			else
				$para_filter[$key] = $para[$key];
		}
		return $para_filter;
	}

	public function juheSign($data, $md5Key) {
		ksort($data);
		reset($data);
		$signString = "";
		foreach ($data as $k => $v) {
			if ($v !== "") {
				$signString.="{$k}={$v}&";
			}
		}
		return strtoupper(md5($signString . "Key={$md5Key}"));
	}

	public function juheSignVerify($data, $md5Key) {
		$sign = $data['Sign'];
		$data = $this->paraFilter($data);
		$mysgin = $this->juheSign($data, $md5Key);
		if ($mysgin == $sign) {
			return true;
		} else {
			return false;
		}
	}

	public function curlPost($url, $data) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
		$content = curl_exec($ch);
		curl_close($ch);
		return $content;
	}

}